<template>
  <div class="custom-body">
    <div v-if="showHeader" class="custom-header" :style="titleStyle">
      <div class="header-body">
        <div v-if="temp.sfxs === true" class="header-icon">
          <i :class="temp.lmtb" />
        </div>
        <div class="header-title">
          <span class="title-span">{{ temp.lmmc }}</span>
        </div>
        <div v-if="temp.isMore === true" class="header-icon">
          更多
        </div>
      </div>
    </div>
    <div class="custom-content">
      <el-scrollbar
        style="width: 100%;height: 100%;overflow-x: hidden;overflow-y: auto"
      >
        <el-empty
          v-if="dataList === null || dataList.length === 0"
          :image-size="100"
        />
        <el-timeline
          v-else
          style="padding-left: 5px;padding-top: 10px;box-sizing: border-box"
        >
          <el-timeline-item
            v-for="item in dataList"
            :key="item.id"
            :icon="item.icon"
            :timestamp="item.createTime"
            color="#E6A23C"
            type="primary"
            :hide-timestamp="true"
            placement="bottom"
          >
            <el-card>
              <div class="custom-time-line">
                <div class="custom-time-body">
                  <div>
                    <h3>标&nbsp;题:&nbsp;{{ item.title }}</h3>
                  </div>
                  <div class="custom-time-button">
                    <el-button
                      type="text"
                      @click="userRead(item)"
                    >未阅</el-button>
                    <el-button
                      v-if="item.openUrl"
                      type="text"
                      @click="openEntity(item)"
                    >查看</el-button>
                  </div>
                  <div>{{ "时&nbsp;间:&nbsp;&nbsp;" + item.createTime }}</div>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
          <div v-if="loading" class="custom-more">加载中...</div>
          <div v-if="disabled" class="custom-more" @click="load">加载更多</div>
          <div v-if="noMore" class="custom-more">没有要加载的数据</div>
        </el-timeline>
      </el-scrollbar>
    </div>
  </div>
</template>
<script>
import { queryAllUnRead, userRead } from '@/api/portal/manager/notice'
import Config from '@/settings'
import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client'
import { getToken } from '@/utils/auth' // getToken from cookie
export default {
  name: 'AppNoticeTempV1', // app消息
  props: {
    temp: {
      type: Object,
      default() {
        return {}
      }
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    layout: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      column: [],
      dataList: [],
      pzx: {},
      loading: false,
      pagerSize: 0,
      disabled: false,
      noMore: false,
      query: {
        page: 1,
        size: 0
      },
      token: getToken(),
      stompClient: null,
      tokenHeader: Config.TokenKey,
      customStyle: {},
      titleStyle: {},
      bodyStyle: {},
      titleFont: {},
      borderStyle: {}
    }
  },
  computed: {
    themes() {
      return this.$store.getters.theme
    }
  },
  watch: {
    layout: {
      handler(newData, oldData) {
        this.customStyle = newData
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    },
    temp: {
      handler(newData, oldData) {
        if (this.showHeader) {
          const pzx = JSON.parse(newData.data.pzx)
          this.pzx = pzx
          this.query.size = pzx.size
        } else {
          const pzx = JSON.parse(newData.pzx)
          this.pzx = pzx
          this.query.size = pzx.size
        }
        this.initAllNotice()
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    },
    themes: {
      handler(val, oldVal) {
        this.borderStyle.borderRadius = val.bkdx
        if (this.temp.sfxsbk === true) {
          this.borderStyle.border = '1px solid ' + val.bkys
        }
        if (this.temp.bkyy === true) {
          this.borderStyle.boxShadow = '0 2px 4px rgba(0, 0, 0, .12)'
        }
        this.borderStyle.background = val.columnGroundColor
        this.borderStyle.color = val.fontColor
        this.titleStyle.background = val.columnTitleGroundColor
        this.titleStyle.color = val.columnTitleFontColor
        this.titleStyle = Object.assign({}, this.titleStyle)
        this.borderStyle = Object.assign({}, this.borderStyle)
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    },
    token(val, oldVal) {
      // 如果一开始没有，现在有了，说明刚登录，连接websocket
      if (!oldVal && val) {
        // this.initWebsocket()
      }
      // 如果原先由，现在没有了，说明退出登录，断开websocket
      if (oldVal && !val) {
        // this.closeWebsocket()
      }
    }
  },
  created() {
    // 只有登录后才连接
    if (this.token) {
      // this.initWebsocket()
    }
  },
  destroyed() {
    // this.closeWebsocket()
  },
  methods: {
    userRead(item) {
      userRead({ noticeId: item.id }).then(res => {
        if (this.dataList.length > this.query.size) {
          this.dataList.splice(item, 1)
        } else {
          this.query.page = 1
          this.dataList = []
          this.initAllNotice()
        }
      })
    },
    openEntity(item) {
      window.open(item.openUrl)
    },
    load() {
      if (this.query.size * (this.query.page + 1) <= this.pagerSize) {
        this.disabled = false
        this.query.page = this.query.page + 1
        this.initAllNotice()
      } else {
        this.noMore = true
        this.disabled = false
        this.loading = false
      }
    },
    initAllNotice() {
      this.loading = true
      queryAllUnRead(this.query)
        .then(res => {
          const { data } = res
          if (undefined !== data && data !== null) {
            this.dataList = this.dataList.concat(data.data)
            this.pagerSize = data.pagerSize
          }
          this.loading = false
          this.disabled = true
        })
        .catch(() => {
          this.dataList = []
          this.pagerSize = 0
          this.loading = false
          this.disabled = false
        })
    },
    initWebsocket() {
      this.stompClient = new Client({
        brokerURL: '', // 可以不赋值，因为后面用SockJS来代替
        connectHeaders: { APEXEDU: this.token },
        debug: function(str) {
          console.log(str)
        },
        reconnectDelay: 10000, // 重连时间
        heartbeatIncoming: 4000,
        heartbeatOutgoing: 4000
      })
      // 用SockJS代替brokenURL
      this.stompClient.webSocketFactory = function() {
        return new SockJS('/socket')
      }
      // 连接
      this.stompClient.onConnect = frame => {
        this.stompClient.subscribe('/user/send/message/notice/all', res => {
          const body = JSON.parse(res.body)
          this.dataList.unshift(body)
          // 解析出对象
        })
        // 新版不用send而是publish
        this.stompClient.publish({
          destination: '/send/hello',
          body: '123'
        })
      }
      // 错误
      this.stompClient.onStompError = function(frame) {
        console.log('Broker reported error: ' + frame.headers['message'])
        console.log('Additional details: ' + frame.body)
        // 这里不需要重连了，新版自带重连 todo 这里先直接报错关闭
        this.closeWebsocket()
      }
      // 启动
      this.stompClient.activate()
    },
    closeWebsocket() {
      if (this.stompClient !== undefined && this.stompClient !== null) {
        this.stompClient.disconnect(() => {
          console.log('关闭链接')
        })
      }
    }
  }
}
</script>

<style scoped>
.custom-body {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-flow: column nowrap;
  border-radius: 4px;
  padding: 0px 0px 10px 0px;
  box-sizing: border-box;
  overflow: hidden;
}
.custom-header {
  width: 100%;
  height: 40px;
  flex: 0 1 auto;
  padding: 0px 10px;
  box-sizing: border-box;
  line-height: 40px;
  cursor: pointer;
}
.header-body {
  width: 100%;
  height: 41px;
  display: flex;
  flex-flow: row nowrap;
}
.title-span {
  height: 40px;
  padding: 12px 5px;
  box-sizing: border-box;
  line-height: 40px;
  text-align: center;
  position: relative;
}
.header-title {
  height: 50px;
  flex: 1 1 auto;
}
.custom-content {
  width: 100%;
  height: auto;
  flex: 1 1 auto;
  padding: 0px 10px;
  overflow: hidden;
  box-sizing: border-box;
}

.custom-content ::v-deep .el-card__body {
  padding: 3px 10px 10px 10px;
}

.custom-content ::v-deep .el-card {
  /* background: #ecf5ff; */
  background: #f5f7fa;
}
/deep/.el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
  overflow-y: auto;
}
.custom-time-line {
  width: 100%;
  min-height: 30px;
  text-align: left;
  padding-right: 20px;
  box-sizing: border-box;
}
.custom-time-body {
  /* border-radius: 2px; */
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12); */
  line-height: 20px;
  padding: 0px 7px;
  box-sizing: border-box;
  /* background-color: #ecf5ff; */
  position: relative;
}
.custom-time-body::before {
  position: absolute;
  top: 8px;
  left: -10px;
  width: 0;
  height: 0;
  overflow: hidden;
  content: "";
  border-color: #ecf5ff transparent transparent;
  border-style: solid dashed dashed;
  border-width: 10px;
}

.custom-time-button {
  position: absolute;
  height: 30px;
  right: 14px;
  bottom: 0px;
  display: none;
}
.custom-time-body:hover .custom-time-button {
  display: block;
}
.custom-more {
  width: 100%;
  height: 20px;
  text-align: center;
  font-size: 12px;
  line-height: 20px;
}
</style>
